/*----------------------------------------------
| noka input v1.0 www.97521.com                 |
| rebin 2014-01-20                             |
|---------------------------------------------*/
var ajaxinputtext = Class.create({
    version: '1.0',
    initialize : function(cfg) {
    	this.id=cfg.id; //id
    	this.cfg = cfg;
    	this.rurl=cfg.rurl;
    	this.icosrc=cfg.rurl+'/nokatag/formcheck/images/exclamation.gif';
    	this.input = $(cfg.id+'_input');
    	this.allownull=cfg.allownull;//是否允许为空
    	this.ico=$(cfg.id+'_img');
    	this.div=$(cfg.id+'_div');
    	this.chtype=cfg.chtype;//验证内型chtype js|server|regex
    	this.verification=cfg.verification;//验证内容
    	this.veriSuccess = cfg.allownull;
    	this.ajaxchtype = false;// 是否正在执行ajva验证
    	this.pva = cfg.pva;//页面参数 ['aaa','ccc']
    	this.readonly=(undefined==cfg.readonly?false:cfg.readonly);
    	this.disabled = (undefined==cfg.disabled?false:cfg.disabled);
    	this.maxclass = cfg.maxclass;
    	this.showpass = (cfg.showpass == undefined?false:cfg.showpass);
    	this.isshow = false;//是否显示
    	this.onShowMax = cfg.onShowMax;
    	this.ismore = (undefined == cfg.ismore?true:cfg.ismore);//是否多项输入
    	this.qulenght=(undefined == cfg.qulenght?2:cfg.qulenght);//查询最大长度
    	this.onchange = cfg.onchange;
    	this.sql = cfg.sql;
    	this.bodyHeight = (cfg.bodyHeight == undefined?200:cfg.bodyHeight);
    	this.json = [];
    	this.selectIndex = -1;//当前选种行
    	this.tempJSON = {};
    	this.vsql = cfg.vsql;
    	this.ndataLang = cfg.ndataLang;
    	this.showhide = cfg.showhide;
    	this.isGrid =(cfg.isGrid == undefined?false:cfg.isGrid);//如果grid模式下禁用方向键
    	this.ondelete = cfg.ondelete;
    	this.dataurl = (undefined== cfg.dataurl?this.rurl+'/nokatag/nselect'+this.id+'.ajaxinput':cfg.dataurl);
    	this.valueurl = (undefined==cfg.valueurl?this.rurl+'/nokatag/nselect'+this.id+'.ajaxinputshows':cfg.valueurl);
    },
    initinput : function(){
    	this.initIco();
    	this.initMsg();
    	this.InputVerEvent();
    	this.msgShowHide();
    	this.initObjCht();
    	this.onChangeColor();
    	this.multinitvalue();
    },
    //---------初始化ico------------------
    initIco : function(){
	   this.ico.src = this.icosrc;
	   this.ico.setStyle({verticalAlign:'middle'});
	   this.ico.hide();
	   this.input.setStyle({verticalAlign:'middle'});
    },
    //---------初始化msgdiv--------------
    initMsg : function(){
    	this.div.setStyle({display:'block',background:'#FFFFFF',border:'solid 1px #FF0000',zIndex:'9999',padding:'5px 5px 5px'});
    	this.div.absolutize();
    	this.div.hide();
    },
    //--------初始化验证-----------------
    initObjCht : function(){
    	var self = this;
    	$(self.id).veri = function(){
    		return self.chVeris();//验证
    	};
    	$(self.id).setValue = function(value,ch){//xiefangjian
    		self.setValues(value,ch);
    	};
    	$(self.id).getValues = function(){
    		var vals='';//值
    		var sals='';//显示值
    		$$('div[id^="'+self.id+'_mulidivs_"]').each(function(alink,index) {
        		vals+=$(alink.id+'_hidden').value+',';
        		sals+=$(alink.id+'_showinput').value+',';
        	});
        	if(vals.indexOf(',')!=-1){
        		vals = vals.substring(0, vals.length-1);	
        	}
        	if(sals.indexOf(',')!=-1){
        		sals = sals.substring(0, sals.length-1);	
        	}
        	return {value:vals,text:sals};
    	};
    	//----------------------------------
    	$(self.id).setDisabled = function(a){
    		$(self.id+'_input').writeAttribute({disabled:a});
    		self.disabled=a;
    	};
    	$(self.id).setReadonly = function(a){
    		$(self.id+'_input').writeAttribute({readonly:a});
    		self.readonly=a;
    	};
    },
    //---------增加验证事件---------------
    InputVerEvent : function(){
    	 var self = this;
    	 self.input.observe('blur',function(){//失失焦点时验证其值
    			self.chVeris();
    	 });
    	//--------------多项输入----------------------------------------
    	 if(!self.isGrid){
	     	 self.input.observe('keyup',function(event){//失失焦点时验证其值
	     		if(event.keyCode == 13) {//回车
		     		if(self.selectIndex>-1){//选择输入
		     				var v=$(self.id+'_'+self.selectIndex+'_value').value;
		        			var t=$(self.id+'_'+self.selectIndex+'_text').value;
		        			self.tempJSON={idx:self.selectIndex,value:v,text:t};
		        			try{$(self.id+'_img').hide();}catch(e){}//隐藏错误消息
		        			self.setMultValue();
		     		}
	     		 }else if(event.keyCode == 40){//40向下
	     			if($(self.id+'_selectbody').visible()){
	     				self.selectBodykeyEvent(false);
	     			}
	     		 }else if(event.keyCode == 38){//38向上
	     			if($(self.id+'_selectbody').visible()){
	     				self.selectBodykeyEvent(true);
					}
	     		 }else if(event.keyCode==27){//27
	     			$(self.id+'_selectbody').hide();
	     		 }else{
	     			self.ajaxSelect();
	     		 }
	     	});
    	 }else{
    		 self.input.observe('keyup',function(event){//失失焦点时验证其值
    			 self.ajaxSelect();
    		 });
    	 }
     	self.selectBodyShowHide();
    },
    //----------------------------------------------------------------------------
    setMultValue : function(){
    	var self = this;
    	var cssStyle = 'nk_ajaxinput_vluediv nk_input_lineheight';
    	var isOnchange = true;//是否继续执行
    	//-----------------------------------------------------------------------
    	try{
	    	if(undefined!=self.onchange){
	    		var ob = {obj:$(self.id),selectvalue:{value:self.tempJSON.value,text:self.tempJSON.text}};
	    		isOnchange = self.onchange(ob);
	    	}
    	}catch(e){}
    	if(false == isOnchange){
    		return;
    	}
    	//------------------------------------------------------
    	if(!self.ismore){//不能多选
    		$(self.id+'_multinput').innerHTML='<div id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'" class="'+cssStyle+'">'+self.tempJSON.text+' <input type="hidden"  id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'_hidden" value="'+self.tempJSON.value+'"><input type="hidden"  id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'_showinput" value="'+self.tempJSON.text+'"></div>';
    	}else{
    		$(self.id+'_multinput').innerHTML+='<div id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'" class="'+cssStyle+'">'+self.tempJSON.text+' <input type="hidden"  id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'_hidden" value="'+self.tempJSON.value+'"><input type="hidden"  id="'+self.id+'_mulidivs_'+self.tempJSON.idx+'_showinput" value="'+self.tempJSON.text+'"></div>';
    	}
    	$(self.id+'_input').value='';
		$$('div[id^="'+self.id+'_mulidivs_"]').each(function(alink,index) {
			$(alink).observe('click',function(){//失失焦点时验证其值
				if(self.deleteUser(alink)){
					$(alink).remove();
					self.multvalue();
				}
			 	try{
			 		$(self.id).focus();
			 	}catch(e){}//显示时，设置焦点
			});
		});
		self.multvalue();
    },
    //-----------------多项输入获取值---------------------------------------
    multvalue : function(){
    	var self = this;
    	var vals = '';
    	$$('div[id^="'+self.id+'_mulidivs_"]').each(function(alink,index) {
    		vals+=$(alink.id+'_hidden').value+',';
    	});
    	if(vals.indexOf(',')!=-1){
    		vals = vals.substring(0, vals.length-1);	
    	}
    	$(self.id).value = vals;
    	if(vals.length>0){
    		$(self.id+'_multinput').show();
    	}else{
    		$(self.id+'_multinput').hide();
    	}
    },
    //============================================================================
    ajaxSelect : function(){
    	var self = this;
    	var idx = 0;//
       	var parsv=[];
       	var val = $(self.id+'_input').value;
       	if(val.length<self.qulenght){
       		return;
       	}
       	parsv[idx++]=(''==self.sql?'':'&sql='+self.sql);
       	parsv[idx++]=('&pare='+val);
    	new Ajax.Request(self.dataurl, {
    	    method:'post',
    	    parameters: parsv.join(''),
    	    onSuccess: function(response) {
    	    	self.json = response.responseText.evalJSON();
    	    	self.jsonList();
    	       }
    	   });
    },
    //------------------------list body--------------------------------
    jsonList : function(){
    	var self = this;
    	var obj = $(self.id+'_input');
    	var pos = obj.positionedOffset();
    	var sebody = $(self.id+'_selectbody');
    	var dtop = pos.top+obj.offsetHeight+2;
    	var dleft = pos.left-1;
    	var idx = 0;
    	var html=[];
    	var Lheight=0;
    	var Lwidth = 0;
    	var AWidth = 2;
    	var json = self.json;
    	sebody.setStyle({width:'',height:''});
    	html[idx++] = '<table id="'+self.id+'_bodytable" style="border:0;" cellpadding="0" cellspacing="0"> ';
    	for(var i=0;i<json.length;i++){
    		html[idx++] = '<tr><td id="'+self.id+'_'+i+'" style="font-size:12px;padding:0;height:25px;color:#000000;" title="'+json[i].text+'" alt="'+json[i].text+'">';
    		html[idx++] = json[i].text;
    		html[idx++] = '<input type="hidden" value="'+json[i].value+'" id="'+self.id+'_'+i+'_value">';
    		html[idx++] = '<input type="hidden" value="'+json[i].text+'"  id="'+self.id+'_'+i+'_text">';
    		html[idx++] = '<input type="hidden" value="'+i+'"  id="'+self.id+'_'+i+'_idx">';
    		html[idx++] = '</td></tr>';
    		Lheight+=28;
    	}
    	if(json.length<1){
    		html[idx++] = '<tr><td style="height:25px;font-size:12px;padding:0;">'+self.ndataLang+'</td></tr>';
    		Lheight+=28;
    	}
    	if(Lheight>self.bodyHeight){
    		Lheight = self.bodyHeight;
    		AWidth+=18;
    	}
    	
    	html[idx++] = '</table>';
    	sebody.innerHTML=html.join('');
    	sebody.setStyle({left:dleft+'px',top:dtop+'px',height:Lheight+'px'});
    	sebody.show();
    	if(undefined!= self.showhide){
    		self.showhide(false);//
    	}
    	Lwidth = $(self.id+'_bodytable').getWidth();
    	IWidth = $(self.id).getWidth();
    	if(Lwidth<IWidth){
    		sebody.setStyle({width:(IWidth+AWidth)+'px'});
    		sebody.style.width=(IWidth+AWidth)+'px';
    	}else{
    		sebody.setStyle({width:(Lwidth+AWidth)+'px'});
    		sebody.style.width=(Lwidth+AWidth)+'px';
    	}
    	self.selectBodyEvent();
    	self.selectIndex=-1;
    	if(json.length>0){
    		self.selectIndex=0;
    		$(self.id+'_0').setStyle({color:'#ffffff',backgroundColor:'#000080'});
    	}
    },
    //-----------------------------------------------------------------
    selectBodyEvent : function(){
    	var self = this;
        var json = self.json;
    	for(var i=0;i<json.length;i++){
    		$(self.id+'_'+i).observe('click',function(a){
    			var v=$(this.id+'_value').value;
    			var t=$(this.id+'_text').value;
    			var idx=$(this.id+'_idx').value;
    			self.tempJSON={idx:idx,value:v,text:t};
    			try{$(self.id+'_img').hide();}catch(e){}
    			self.setMultValue();
            });
    		$(self.id+'_'+i).observe('mousemove',function(a){
    			this.setStyle({color:'#ffffff',backgroundColor:'#000080'});
            });
    		$(self.id+'_'+i).observe('mouseout',function(a){
    			this.setStyle({color:'#000000',backgroundColor:'#ffffff'});
            });
    	}
    },
    selectBodykeyEvent : function(a){
    	var self = this;
    	var json = self.json;
    	var mx = json.length-1;
    	var sm = (self.bodyHeight/27)-1;
    	try{
	    	try{
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#000000',backgroundColor:'#ffffff'});//设置上一个选择项为未选择状态
	    	}catch(e){}
	    	if(a){//向上
	    		self.selectIndex--;
	    		if(self.selectIndex<0){
	    			self.selectIndex=0;
	    		}
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#ffffff',backgroundColor:'#000080'});
	    		$(self.id+'_selectbody').scrollTop-= (((sm+2)-self.selectIndex)*27);
	    	}else{//向下
	    		self.selectIndex++;
	    		if(self.selectIndex>mx){
	    			self.selectIndex=mx;
	    		}
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#ffffff',backgroundColor:'#000080'});
	    		$(self.id+'_selectbody').scrollTop+= ((self.selectIndex-sm)*27);
	    	}
    	}catch(es){}
    },
    selectBodyShowHide : function(){
    	var self = this;
    	var miFlg = true;
    	var obj = $(self.id+'_input');
    	var tre = $(self.id+'_selectbody');
    	var sdy = $(self.id+'_sdDiv');
    	obj.observe('mousemove',function(){
    		miFlg = true;
    	});
        obj.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(sdy) && !miFlg){
                	tre.hide();
                	if(undefined!= self.showhide){
                		self.showhide(true);//
                	}
                }
            }, 500);
        });
        tre.observe('mousemove',function(){
    		miFlg = true;
    	});
        tre.observe('click',function(){
    		miFlg = true;
    	});
        tre.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(tre) && !miFlg){
                	tre.hide();
                	if(undefined!= self.showhide){
                		self.showhide(true);//
                	}
                }
            }, 200);
        });
        document.observe('widget:noka_reinit',function(event){//失失焦点时验证其值
        	if(self.id.indexOf('_nkADinsert_')==-1){
     	    	var npfffs=event.memo.widgetNumber.clone();
     	    	for(var i=0;i<npfffs.length;i++){
     	    		var cfgid = Object.allclone(self.cfg);
     	    		var initem = npfffs[i];
     	    		cfgid.id = initem.id;
     	    		if(undefined!=initem.value){
     	    			cfgid.value = initem.value;
     	    		}
     	    		if(cfgid.id.indexOf('_'+self.id+'_')!=-1){
     	    			(new ajaxinputtext(cfgid)).initinput();
     	    			try{
	    					var idx = cfgid.id.substring(cfgid.id.lastIndexOf('_')+1,cfgid.id.length);
	    					$(cfgid.id).name=$(cfgid.id).name.replace(/\[0\]/g,'['+idx+']');
	    					if(undefined!=initem.value && $(cfgid.id).name==initem.name){
	    						$(cfgid.id).setValue(initem.value);
	    					}
	    				}catch(e){}
     	    		}
     	    	}
        	}
        });
    },
    //================================================================================
    multinitvalue : function(){
    	var self = this;
    	self.ajaxValues();
    },
    //------------设置值-----------------------------------------------------------------
    setValues : function(vals,ch){
    	var self = this;
    	$(self.id).value = vals;
    	if(typeof ch == 'undefined'){//验证
    		self.chVeris();
    	}
    	$(self.id+'_input').value = '';//清空输入框
    	$(self.id+'_multinput').innerHTML='';//清空显示内容
    	self.ajaxValues();
    },
    ajaxValues : function(){
    	var self = this;
    	var idx = 0;//
       	var parsv=[];
       	var val = $(self.id).value;
       	if(val.trim().length<1){
       		return;
       	}
       	parsv[idx++]=(''==self.vsql?'':'&sql='+self.vsql);
       	parsv[idx++]=('&pare='+val);
    	new Ajax.Request(self.valueurl, {
    	    method:'post',
    	    parameters: parsv.join(''),
    	    onSuccess: function(response) {
    	    	//-----------------------------------------------------------------
    	    	var json = response.responseText.evalJSON();
    	    	var cssStyle = 'nk_ajaxinput_vluediv nk_input_lineheight';
    	    	$(self.id+'_multinput').innerHTML='';
    	    	$(self.id).value='';
    	    	for(var i=0;i<json.length;i++){
    	    		var idx = i+999;
    	    		$(self.id+'_multinput').innerHTML+='<div id="'+self.id+'_mulidivs_'+idx+'" class="'+cssStyle+'">'+json[i].text+' <input type="hidden"  id="'+self.id+'_mulidivs_'+idx+'_hidden" value="'+json[i].value+'"><input type="hidden"  id="'+self.id+'_mulidivs_'+idx+'_showinput" value="'+json[i].text+'"></div>';
    	    	}
    			$$('div[id^="'+self.id+'_mulidivs_"]').each(function(alink,index) {
    				$(alink).observe('click',function(){//失失焦点时验证其值
    					if(self.deleteUser(alink)){
    						$(alink).remove();
    						self.multvalue();
    					}
    				 	try{
    				 		$(self.id).focus();
    				 	}catch(e){}//显示时，设置焦点
    				});
    			});
    			self.multvalue();
    			//-------------------------------------------------------------------
    	       }
    	   });
    },
    deleteUser : function(alink){
    	var self = this;
    	var isremove = true;
    	if(self.readonly || self.disabled){
    		return false;
    	}
		try{
			if(undefined !=self.ondelete){
				var ab = $(alink);
				
				var ob = {obj:$(alink),valueobj:$(ab.id+'_hidden'),showobj:$(ab.id+'_showinput')};
				isremove = self.ondelete(ob);
			}
			if(undefined == isremove){
				isremove = true;
			}
		}catch(e){}
		return isremove;
    },
    //---------------------------------------------------------------------------------
    chVeris : function(){
    	var self = this;
    	var vale = $(self.id).value;
    	if(self.allownull){//允许为空
    		self.ico.hide();
    		return true;
    	}else if(vale.trim().length>0){//不允许为空，值大于1，返回true
    		self.ico.hide();
    		return true;
    	}else{
    		self.ico.show();
    		return false;
    	}
    },
    //--------regex------------------------
    chInputRegex : function(value){
    	var regu = "^" + this.verification + "$";
    	var re = new RegExp(regu);
    	return re.test(value);
    },
    //--------消息提示显示、隐藏------------
    msgShowHide : function(){
    	var self = this;
   	 	self.ico.observe('mousemove',function(){//失失焦点时验证其值
   	 		if(self.ico.visible){//图标可见
   	 			self.div.absolutize();
   	 			self.div.style.top=self.ico.positionedOffset().top+self.ico.offsetHeight;//
   	 			self.div.style.left=self.ico.positionedOffset().left+self.ico.offsetWidth;
   	 			self.div.setStyle({top:(self.ico.positionedOffset().top+self.ico.offsetHeight)+'px',left:(self.ico.positionedOffset().left+self.ico.offsetWidth)+'px'});
   	 			self.div.show();
   	 		}
   	 	});
   	 	self.ico.observe('mouseout',function(event){
	   	 	if(self.div.visible){//图标可见
		 		self.div.hide();
		 	}
   	 	});
    },
    onChangeColor : function(){
    	var self = this;
    	var obj = $(self.id+'_sdDiv');
    	obj.observe('mousemove',function(){
     		self.setSelectStyle(obj);
     	});
    	
         obj.observe('mouseout',function(event){
         	var element = event.element();
         	setTimeout(function(){
                 	self.setNoSelectStyle(obj);
             }, 500);
         });
    },
    //----------选种状态-----------------------
    setSelectStyle : function(obj){
    	obj.setStyle({borderColor:'#5794bf'});
    },
    //-----------未选种状态-------------------
    setNoSelectStyle : function(obj){
    	obj.setStyle({borderColor:'#AFAFAF'});
    }
});